package vip.zhenzicheng.nettybasic.embedded;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 扩展实现消息的解码
 *
 * @author zhenzicheng
 * @date 2022-06-13 11:52
 */
public class FixedLengthFrameDecoder extends ByteToMessageDecoder {

  private final int frameLength;

  public FixedLengthFrameDecoder(int frameLength) {
    if (frameLength <= 0) {
      throw new IllegalArgumentException("frameLength must be a positive integer：" + frameLength);
    }
    this.frameLength = frameLength;
  }

  @Override
  protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
    if (byteBuf.readableBytes() >= this.frameLength) { // 如果有足够的字节可以被读取，生成下一帧
      ByteBuf buf = byteBuf.readBytes(frameLength); // 读取一个新帧
      list.add(buf); // 写入
    }
  }
}
